<template>
  <!-- wel-中的详细主机, echarts 图表 -->
  <div class="wel-detail-host">
    <!-- 下拉菜单 -->
    <el-select
      class="host-seclect"
      v-model="selectHostValue"
      filterable
      placeholder="请选择你要查看的主机"
     @change="selectchange()"
    >
      <el-option
        v-for="item in selectHost"
        :key="item"
        :value="item"
      ></el-option>
    </el-select>

    <!-- cup -->
    <div id="cpu" class="some some-cpu"></div>
    <img id="linear-pic" src="../../static/img/wel仪表盘渐变颜色图片.jpg" alt="wel仪表盘渐变颜色图片" style="display: none">
    <!-- disk -->
    <div id="disk" class="some some-disk"></div>
    <!-- memory -->
    <div id="memory" class="some some-memory"></div>
    <!-- network -->
    <div id="net" class="some some-network"></div>
  </div>
</template>
<script>
import echarts from 'echarts'


import {
  getHostList,
  getNet,
  getMemory,
  getCpu,
  getDisk
} from "@/api/wel.js";

// 颜色序列
let colorList = ['rgba(148, 104, 243, 1)' ,'#53ccb8', 'rgba(66, 162, 255, 1)','#cecece', '#305e80']
// 整个echarts表颜色主题
let colorThemeNum =parseInt(Math.random() * 100 % colorList.length);
// 随机生成的颜色序列
let randomColorList = function () {
  // slice默认截取到最后
  let arr = colorList.slice(colorThemeNum);
  arr = arr.concat(colorList.slice(0, colorThemeNum));
  return arr;
}();
console.log("======",randomColorList)
// 四个图的标题样式
let echartsTitleStyle = {color: randomColorList[4]}

// 折线图的颜色样式配置
let nameTextStyle = {color:randomColorList[2]}
let yAxisLabelStyle = {color:randomColorList}
let xAxisLabelStyle =  {color:randomColorList}
let yAxisStyle = function (name) {
  return{
    type: "value",
    name: name,
    nameTextStyle: nameTextStyle,
    axisLine: {
      lineStyle: {color: randomColorList[3]}
    },
    axisLabel: yAxisLabelStyle
  }
}
let xAxisStyle = function (name) {
  return {
    type: "category",
    splitLine: {
      show: false,
    },
    name: name,
    data: [],
    boundaryGap: false,
    axisLabel: xAxisLabelStyle,
    axisLine: {
      lineStyle: {color: randomColorList[3]}
    }
  }
}




export default {
  name: 'WelDetailHost',
  data() {
    return {
       // echarts 实例
      cpuEchartsInstance: null,
      memoryEchartsInstance: null,
      diskEchartsInstance: null,
      netEchartsInstance: null,
      // 下拉菜单选择的主机列表
      selectHost: {},
      // 下拉菜单选中的主机
      selectHostValue: "",
         // 某一个主机的 cpu 配置选项
      cpuOption: {
        title: {
          text: "CPU利用率",
          textStyle: echartsTitleStyle
        },
        series:[]
      },

      diskOption: {
        title: {
          text: "硬盘使用情况",
          textStyle: echartsTitleStyle
        },
        tooltip: {
          formatter: "{b}: {c} MB"
        },
      color: ['#6d94b0', '#c4dff1'],
        series: {
          type: "pie",
          radius: "70%",
          data: [
            { name: "已使用", value: null },
            { name: "未使用", value: null }
          ]
        }
      },
       // 某一个主机的 memory 配置选项
      memoryOption: {
        title: {
          text: "內存",
          textStyle: echartsTitleStyle
        },
        tooltip: {
          trigger: "axis",
        },
        xAxis: xAxisStyle(''),
        yAxis: yAxisStyle("单位 (MB)"),
        dataZoom: [
          // 缩放
          {
            type: "slider",
            xAxisIndex: 0,
            filterMode: "empty"
          }
        ],
        color: randomColorList,
        series: [
          {
            showSymbol: false,
            hoverAnimation: false,
            name: "內存",
            type: "line",
            data: []
          }
        ]
      },
      // 某一个主机的 network 配置选项
      netOption: {
        title: {
          text: "网络情况",
          textStyle: echartsTitleStyle
        },
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: ["上传", "下载"]
        },
        xAxis: xAxisStyle('时间'),
        yAxis: yAxisStyle('单位 (Kbps)'),
       color: ['rgba(148, 104, 243, 1)', '#c4dff1'],
        dataZoom: [
          // 缩放
          {
            type: "slider",
            xAxisIndex: 0,
            filterMode: "empty"
          }
        ],
        series: [
          {
            symbol: "none",
            name: "上传",
            type: "line",
            data: []
          },
          {
            symbol: "none",
            name: "下载",
            type: "line",
            data: []
          }
        ]
      },


    }
  },
  created() {
    this.cpuOption.series = this.initCpuOptionSeries();
    this.getHostList();
    this.getSomeHost();
  },
  methods: {
      // 画图表, 接收字符串dom元素
    drawChart(elStr) {
      this[elStr + "EchartsInstance"] = echarts.init(
        document.getElementById(elStr)
      );
      this[elStr + "EchartsInstance"].setOption(this[elStr + "Option"]);
    },
     drawCpu(elStr) {
      this[elStr + "EchartsInstance"] = echarts.init(
        document.getElementById(elStr)
      );
      this[elStr + "Option"].series = this.setCpuOptionSeries();
      this[elStr + "EchartsInstance"].setOption(this[elStr + "Option"]);
    },

    // 请求数据，请求完了之后自动调用 drawChart方法
    getSomeHost() {
      this.getCpu(this.selectHostValue);
      this.getDisk(this.selectHostValue);
      this.getMemory(this.selectHostValue);
      this.getNet(this.selectHostValue);
    },

    getHostList() { // 读取主机列表
      getHostList()
        .then(response => {
            if (response.status === 200) {
              for (let i = 0; i < response.data.length; i++) {
                this.selectHost[i] = response.data[i].host;
              }
            } else {
              console.log("请求数据失败");
            }
            this.selectHostValue = this.selectHost[0];
            this.selectchange();
            console.log('----------',this.selectHost)
          })
        .catch(err => {
          throw err;
        });
    },
    getCpu(host) { // 读取 CPU
      getCpu(host)
        .then(response => {
          if (response.status === 200) {
            this.setCpuOptionSeriesValue(response.data.cpu.value)
            this.drawChart("cpu");
          } else {
            console.log("读取 cpu 失败");
          }
        })
        .catch(err => {
          throw err;
        });
    },
    getDisk(host) { // 读取 disk
      getDisk(host)
        .then(response => {
          if (response.status === 200) {
            let disk = response.data.disk;
            this.diskOption.series.data[0].value = disk.used;
            this.diskOption.series.data[1].value = disk.unused;
            this.drawChart("disk");
          } else {
            console.log("读取 disk 失败");
          }
        })
        .catch(err => {
          throw err;
        });
    },
    getMemory(host) { // 读取 memory
      getMemory(host)
        .then(response => {
          if (response.status === 200) {
            let len = response.data[0].memory.length;
            for (let i = 0; i < len; i++) {
              let clock = response.data[0].memory[i].clock;
              let value = response.data[0].memory[i].value / 1024;
              this.memoryOption.xAxis.data.push(this.timestampToTime(clock));
              this.memoryOption.series[0].data.push(this.kBToMB(value));
              this.drawChart("memory");
            }
          } else {
            console.log("读取 memory 失败");
          }
        })
        .catch(err => {
          throw err;
        });
    },
    getNet(host) {// 读取 network
      getNet(host)
        .then(response => {
          if (response.status === 200) {
            let len = response.data[0].net.length; // 56
            for (let i = 0; i < len; i++) {
              let clock = response.data[0].net[i].clock;
              let upValue = response.data[0].net[i].value;
              let downValue = response.data[1].net[i].value;
              this.netOption.xAxis.data.push(this.timestampToTime(clock));
              this.netOption.series[0].data.push(this.bpsToKbps(upValue));
              this.netOption.series[1].data.push(this.bpsToKbps(downValue));
            }
            this.drawChart("net");
          } else {
            console.log("读取 net 失败");
          }
        })
        .catch(err => {
          throw err;
        });
    },

    cleardata() {
      this.netOption.series[0].data = [];
      this.netOption.series[1].data = [];
      this.netOption.xAxis.data = [];
      this.memoryOption.series[0].data = [];
      this.memoryOption.xAxis.data = [];
    },

    //下拉列表选择事件
    selectchange() {
      this.cleardata();
      this.getSomeHost();
    },
     // 时间戳转换为时间
    timestampToTime(timestamp) {
      let date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      let h = date.getHours() + ":";
      let m =
        date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      return h + m;
    },
    bpsToKbps(value) {
      return this.toDecimal(value / 1000);
    },
    kBToMB(value) {
      return this.toDecimal(value / 1024);
    },
    toDecimal(x) {
      let f = parseFloat(x);
      if (isNaN(f)) {
        return;
      }
      f = Math.round(x * 100) / 100;
      return f;
    },

    // 初始化CPU的配置选项里的series
    initCpuOptionSeries (value) {
      let offsetAngle = -35;
      let totalAngle = 250;
      let split = 75;
      let series = [];
      let asisWidth = 11;
      let fontSize = 30;
      let params = {
          min: 0,
          max: 100,
          name: 'CPU usage rates',
          type: 'gauge',
          data: [{
              value: 0,
              name: ''
          }]
      }
      params.value = value || 100;

      let startAngle = totalAngle + offsetAngle;
      let endAngle = startAngle - Math.floor((parseInt(params.value, 10) / (params.max - params.min)) * totalAngle);

      series.push({
          name: params.name,
          type: params.type,
          startAngle: startAngle,
          endAngle: endAngle,
          splitNumber: 1,
          // 轴线样式
          axisLine: {
              show: false,
              lineStyle: {
                  width: asisWidth,
                  opacity: 0
              }
          },
          // 分段样式
          splitLine: { show: false },
          // 刻度样式
          axisTick: {
              length: asisWidth,
              splitNumber: Math.floor((params.value / (params.max - params.min)) * split),
              lineStyle: {
                  color: {
                      image: document.getElementById('linear-pic'),
                      repeat: 'no-repeat'
                  },
                  width: 2
              }
          },
          axisLabel: { show: false },
          pointer: { show: false },
          // 指针样式
          itemStyle: {},
          title: {
              fontSize: 12,
              offsetCenter: [0, '-35%'],
              color: '#999'
          },
          detail: {
              color: '#36444b',
              fontSize: fontSize,
              offsetCenter: [0, '20%'],
              formatter: function (val) {
                  return val.toFixed(2) + '{unit| %}'
              },
              rich: {
                  unit: {
                      fontSize: 12,
                      color: '#999',
                      lineHeight: 30
                  }
              }
          },
          data: [{
              value: params.value,
              name: params.name
          }]
      });
      // 灰色的圈 ----未使用的
      series.push({
          name: '',
          type: params.type,
          startAngle: endAngle,
          endAngle: offsetAngle,
          splitNumber: 1,
          axisLine: {
              show: false,
              lineStyle: {
                  width: asisWidth,
                  opacity: 0
              }
          },
          splitLine: { show: false },
          axisTick: {
              length: asisWidth,
              splitNumber: split - Math.floor((params.value / (params.max - params.min)) * 80),
              lineStyle: {
                  color: 'rgba(0,0,0, 0.2)',
                  width: 2
              }
          },
          axisLabel: { show: false },
          pointer: { show: false },
          // 指针样式
          itemStyle: {},
          title: { show: false },
          detail: { show: false }
      });
      return series;
    },
    // 设置CPU的配置选项里的series value
    setCpuOptionSeriesValue (value) {
      let offsetAngle = -35;
      let totalAngle = 250;
      let split = 75;
      let asisWidth = 11;
      let fontSize = 30;
      let cpu = {min:0, max:100,value};
      cpu.value = value || 100;
      let startAngle = totalAngle + offsetAngle;
      let endAngle = startAngle - Math.floor((parseInt(cpu.value, 10) / (cpu.max - cpu.min)) * totalAngle);
      this.cpuOption.series[0].startAngle = startAngle;
      this.cpuOption.series[0].endAngle = endAngle;
      this.cpuOption.series[0].axisTick.splitNumber = Math.floor((cpu.value / (cpu.max - cpu.min)) * split);
      this.cpuOption.series[0].axisTick.lineStyle.color.image = document.getElementById('linear-pic');
      this.cpuOption.series[0].data[0].value = cpu.value;
      // 第二个 灰色的圈
      this.cpuOption.series[1].startAngle = endAngle;
      this.cpuOption.series[1].startendAngleAngle = offsetAngle;
      this.cpuOption.series[1].axisTick.splitNumber = split - Math.floor((cpu.value / (cpu.max - cpu.min)) * 80);
    }
  },
};
</script>
<style lang="scss" scope>
.wel-detail-host {
  .el-input__inner {
    background-color: rgba(255, 253, 253, 0.164);
  }
  margin: 0 10px;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.53);
  .some {
    float: left;
    width: 48%;
    height: 300px;
    margin: 15px 0 0 15px;
    box-sizing: border-box;
  }
}
.wel-detail-host::after {
  content: "";
  display: block;
  clear: both;
}
</style>
